package com.netty.rpc.client;

import com.netty.rpc.client.handler.RpcResponseMessageHandler;
import com.netty.rpc.message.RpcRequestMessage;
import com.netty.rpc.protocol.MessageCodecSharable;
import com.netty.rpc.protocol.ProcotolFrameDecoder;
import com.netty.rpc.server.service.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class RpcClientManager {

    private static volatile Channel channel;
    private static final Object LOCK=new Object();
    private static final AtomicInteger ato=new AtomicInteger();

    public static <T> T getFeignService(Class<T> clazz){
        Object instance = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                int sequenceId = ato.getAndIncrement();
                RpcRequestMessage rpcRequestMessage = new RpcRequestMessage(
                        sequenceId,
                        clazz.getName(),
                        method.getName(),
                        method.getReturnType(),
                        method.getParameterTypes(),
                        args
                );
                getChannel().writeAndFlush(rpcRequestMessage);
                DefaultPromise<Object> promise=new DefaultPromise<>(channel.eventLoop());
                RpcResponseMessageHandler.PROMISE_MAP.put(sequenceId,promise);
                promise.await();
                if (promise.isSuccess()){
                    return promise.get();
                }else {
                    throw new RuntimeException(promise.cause());
                }
            }
        });
        return (T)instance;
    }

    private static Channel getChannel(){
        if (channel==null){
            synchronized (LOCK){
                if (channel==null){
                    initChannel();
                }
            }
        }
        return channel;
    }

    private static void initChannel(){
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcResponseMessageHandler RPC_RESPONSE_MESSAGE_HANDLER=new RpcResponseMessageHandler();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                nioSocketChannel.pipeline().addLast(new ProcotolFrameDecoder());
                nioSocketChannel.pipeline().addLast(LOGGING_HANDLER);
                nioSocketChannel.pipeline().addLast(MESSAGE_CODEC);
                nioSocketChannel.pipeline().addLast(RPC_RESPONSE_MESSAGE_HANDLER);
            }
        });
        try {
            ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync();
            channel = future.channel();
            // 成功建立链接
            future.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    group.shutdownGracefully();
                    log.debug("【{}】连接已关闭",this);
                }
            });
        } catch (InterruptedException e) {
            log.error("client is error");
        }
    }

}
